import React, {createContext, useState} from 'react'
import classNames from 'classnames'

type MenuMode = 'horizontal' | 'vertical'
type SelectCallback = (selectIndex: number) => void;
export interface MenuProps {
    defaultIndex?: number;
    className?:string;
    mode?:MenuMode;
    style?: React.CSSProperties;
    onSelect?: SelectCallback
    children: React.ReactNode;
}

interface IMenuContext {
    index: number;
    onSelect?: SelectCallback;
}

export const MenuContext = createContext<IMenuContext>({index:0});

const Menu: React.FC<MenuProps> = (props) => {
    const {
        className,
        mode,
        defaultIndex,
        style,
        children,
        onSelect
    } = props

    const [currentActive, setActive] = useState(defaultIndex);
    const classes = classNames('menu', className, {
        'menu-vertical': mode==='vertical'
    })

    const handleClick = (index: number) => {
        setActive(index);
        onSelect && onSelect(index);
    }
    const passContext: IMenuContext = {
        index: currentActive ? currentActive : 0,
        onSelect: handleClick
    }
    return (
        <ul className={classes} style={style}>
            <MenuContext.Provider value={passContext}>
                {children}
            </MenuContext.Provider>
        </ul>
    )
}

export default Menu;